import {Component} from 'react';
import { Button,message } from "antd";
import {getSms} from '../../api/account'

class CodeBtn extends Component {
  constructor(props) {
    super(props);
    this.state = {
      btnText:'获取验证码',//发送中，60s ，重新获取
      disabled: false, //需要外面传入--是否禁用按钮
      num:10,
      timer:null,
      loading:false,
      username:this.props.username || '', // 外面传入
      module:this.props.module || '' // 外面传入
    };
  }
  componentWillReceiveProps(props){
    if(props.username !== this.state.username){
      this.setState({
        username:props.username
      })
    }
  }
  componentWillUnmount(){
    clearInterval(this.state.timer)
  }
  handleCode=async ()=>{
    const {username,module} = this.state
    const res = await getSms({username,module})
   const {resCode} = res
   resCode===0 ? message.success(res.message) :  message.warn(res.message) 
  }
   getCode=()=>{
    //  一种是就用组件提供的btn来做 就是样式可能会有点丑  还有一种就是只写写一个div来做 
    const {disabled,timer,username} = this.state
    if(username === ''){
      return  message.warning('请输入用户邮箱！！！');
    }
    let {num} =  this.state
    const _this = this
    if(disabled)return
    if(timer){
      clearInterval(timer)
      this.setState({
        timer:null
      })
      return 
    }
    // 发送请求
    this.handleCode()
    this.setState({
      btnText:'发送中',
      loading:true
    })
    const timers = setInterval(() => {
       num--
      _this.setState({
        btnText:num+'s',
        timer:timers
      })
      if(num<0){
        clearInterval(timers)
        _this.setState({
          timer:null,
          btnText:'重新获取',
          loading:false,
          disabled:false
        })
        return 
      }
    }, 1000);



  }
  render() {
    const {btnText,disabled,loading} = this.state
    return (
      <Button type="danger" htmlType="submit" block onClick={this.getCode} disabled={disabled} loading={loading}>
         {btnText}
      </Button>
    );
  }
}

export default CodeBtn;
